package com.suneast.suneaststore.modules.personal.order.fragment;

import android.Manifest;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.bean.personal.order.FastOrderDetailBean;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.common.PictureHandler;
import com.suneast.suneaststore.modules.common.event.PicUploadResult;
import com.suneast.suneaststore.modules.personal.order.OrderHandler;
import com.suneast.suneaststore.modules.personal.order.adapter.FastOrderAdapter;
import com.suneast.suneaststore.modules.personal.order.event.FastOrderSetResult;
import com.suneast.suneaststore.modules.personal.order.event.GotFastOrderResult;
import com.suneast.suneaststore.modules.shopcart.HandlePayFragment;
import com.suneast.suneaststore.ui.fragments.BaseFragmentWithDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.noobie.photopicker.common.Global;
import org.noobie.photopicker.entity.Photo;
import org.noobie.photopicker.ui.PhotoPickerFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class FastOrderDetail extends BaseFragmentWithDialog {
    private final static String TAG = FastOrderDetail.class.getSimpleName();
    private final static int RequestCode = TAG.hashCode();
    private int orderId = -1;

    @Override
    public int setLayout() {
        return R.layout.fragment_fast_order_detail;
    }

    public FastOrderDetail withId(int orderId) {
        this.orderId = orderId;
        return this;
    }

    @OnClick({R.id.btn_handle_fast_order_01, R.id.btn_handle_fast_order_02,
            R.id.btn_commit_order_reply, R.id.btn_cancel_order})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.btn_handle_fast_order_02: {
                if (adapter.getState() == Flag.FastOrderState.MERCHANT_CHECKED) {
                    //支付订单
                    start(new HandlePayFragment().withId(orderId));
                } else if (adapter.getState() == Flag.FastOrderState.MERCHANT_SENT) {
                    //todo 确认收货
                } else if (adapter.getState() == Flag.FastOrderState.CUSTOMER_PAYED) {
                    //确认发货
                    start(new ConfirmDeliveredFragment().withOrderId(orderId).withPos(0));
                }
            }
            break;
            case R.id.btn_handle_fast_order_01: {
                if (adapter.getState() == Flag.FastOrderState.MERCHANT_CHECKED) {
                    //取消订单
                    OrderHandler.cancelOrder(orderId, "取消快速下单", -1);
                }
            }
            break;
            case R.id.btn_commit_order_reply: {
                if (detailBean != null) {
                    //从recyclerview中的EditText获取回复信息
                    for (int i = 0, iLength = adapter.getData().size(); i < iLength; i++) {
                        EditText et = (EditText) adapter.getViewByPosition(i, R.id.et_explain);
                        if (et != null) {
                            String replyText = et.getText().toString();
                            if (replyText.length() > 0) {
                                replyTexts.append(i, replyText);
                            }
                        }
                    }
                    int gallerySize = detailBean.getGallery().size();
                    //检查用户是否填写完整
                    if (replyImgUrls.size() == gallerySize || replyTexts.size() == gallerySize) {
                        if (pricingEt.getText().length() == 0) {
                            Toast.makeText(_mActivity, "请填写订单的价格",
                                    Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            double price = Double.valueOf(pricingEt.getText().toString());
                            ArrayList<String> urlList = new ArrayList<>();
                            ArrayList<String> textList = new ArrayList<>();
                            for (int i = 0; i < gallerySize; i++) {
                                String url = replyImgUrls.get(i);
                                urlList.add(url == null ? "" : url);
                                String text = replyTexts.get(i);
                                textList.add(text == null ? "" : text);
                            }
                            Log.e(TAG, "onViewClick: " + urlList.size() + "---" + textList.size());
                            OrderHandler.setFastOrder(orderId, price, JSON.toJSONString(urlList),
                                    JSON.toJSONString(textList));
                        }
                    } else {
                        Toast.makeText(_mActivity, "每个图片至少要有一个文字回复或图片回复",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            }
            break;
            case R.id.btn_cancel_order: {

            }
            break;
        }
    }

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_order_state)
    TextView orderStateTv;
    @BindView(R.id.tv_info)
    TextView infoTv;
    @BindView(R.id.rv_fast_order_content)
    RecyclerView orderContentRv;
    @BindView(R.id.tv_price)
    TextView priceTv;
    @BindView(R.id.tv_demand)
    TextView demandTv;
    @BindView(R.id.tv_pricing_title)
    TextView pricingTitleTv;
    @BindView(R.id.et_pricing)
    EditText pricingEt;
    @BindView(R.id.layout_handle_order)
    LinearLayout handleOrderLayout;
    @BindView(R.id.layout_confirm_order)
    ConstraintLayout confirmOrderLayout;
    @BindView(R.id.btn_handle_fast_order_01)
    Button handleOrderBtn01;
    @BindView(R.id.btn_handle_fast_order_02)
    Button handleOrderBtn02;

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        initData();
        initView();
        if (orderId != -1) {
            OrderHandler.requestFastOrderDetail(orderId);
        }
    }

    private int selectPos = -1;
    private SparseArray<String> replyImgUrls;
    private SparseArray<String> replyTexts;

    private void initData() {
        replyImgUrls = new SparseArray<>();
        replyTexts = new SparseArray<>();
    }

    private FastOrderAdapter adapter;

    private void initView() {
        toolbar.setNavigationOnClickListener((View v) -> pop());
        orderContentRv.setLayoutManager(new LinearLayoutManager(_mActivity));
        adapter = new FastOrderAdapter(R.layout.item_fast_order_committed);
        adapter.setOnItemChildClickListener((BaseQuickAdapter adapter, View view, int position) -> {
            //调起图片选择器
            if (selectPos == -1) {
                selectPos = position;
                FastOrderDetailPermissionsDispatcher.startPickerFragmentWithPermissionCheck(this);
            }
        });
        adapter.bindToRecyclerView(orderContentRv);
    }

    FastOrderDetailBean detailBean = null;
    private int userType = 0;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotFastOrder(GotFastOrderResult event) {
        if (event.getResult() == Flag.Result.SUCCEED) {
            detailBean = event.getBean();
            userType = detailBean.getUsertype();
            infoTv.setText(getInfoText(detailBean.getAddress()));
            demandTv.setText(detailBean.getDemand());
            if (detailBean.getState() == 1) {//此订单未定价
                if (userType == 0) { // 订单发起者查看此订单
                    adapter.setState(Flag.FastOrderState.MERCHANT_CHECKING);
                    orderStateTv.setText("等待审核定价");
                } else {//订单应答者查看此订单
                    adapter.setState(Flag.FastOrderState.CUSTOMER_COMMITTED);
                    orderStateTv.setText("审核定价");
                    pricingTitleTv.setVisibility(View.VISIBLE);
                    pricingEt.setVisibility(View.VISIBLE);
                    confirmOrderLayout.setVisibility(View.VISIBLE);
                }
            } else if (detailBean.getState() == 2) {//此订单已定价
                priceTv.setVisibility(View.VISIBLE);
                priceTv.setText(String.format(_mActivity.getResources()
                        .getString(R.string.price_hint), detailBean.getPrice()));
                pricingTitleTv.setVisibility(View.GONE);
                pricingEt.setVisibility(View.GONE);
                if (userType == 0) { // 订单发起者查看此订单
                    switch (detailBean.getStatus()) {
                        case 0: {//未付款
                            adapter.setState(Flag.FastOrderState.MERCHANT_CHECKED);
                            orderStateTv.setText("支付订单");
                            handleOrderLayout.setVisibility(View.VISIBLE);
                            handleOrderBtn01.setVisibility(View.VISIBLE);
                            handleOrderBtn01.setText(_mActivity.getString(R.string.cancel_order));
                            handleOrderBtn02.setText(_mActivity.getString(R.string.pay_order));
                        }
                        break;
                        case 1: {//已付款,未发货
                            adapter.setState(Flag.FastOrderState.MERCHANT_SENDING);
                            orderStateTv.setText("等待发货");
                        }
                        break;
                        case 2: {//已发货,用户未确认收货
                            adapter.setState(Flag.FastOrderState.MERCHANT_SENT);
                            orderStateTv.setText("确认收货");
                            handleOrderLayout.setVisibility(View.VISIBLE);
                            handleOrderBtn02.setText("确认收货");
                        }
                        break;
                        case 3: {//交易完成 无法判断是否评价
                            adapter.setState(Flag.FastOrderState.BUSINESS_FINISHED);
                            handleOrderLayout.setVisibility(View.GONE);
                            orderStateTv.setText("交易已完成");
                        }
                        break;
                        case -1: {//订单已取消
                            adapter.setState(Flag.FastOrderState.ORDER_CANCELED);
                            orderStateTv.setBackgroundColor(Color.LTGRAY);
                            handleOrderLayout.setVisibility(View.GONE);
                            orderStateTv.setText("订单已取消");
                        }
                        break;
                    }
                } else {//订单应答者查看此订单
                    switch (detailBean.getStatus()) {
                        case 0: {//未付款
                            adapter.setState(Flag.FastOrderState.CUSTOMER_PAYING);
                            orderStateTv.setText("等待客户付款");
                        }
                        break;
                        case 1: {//已付款
                            adapter.setState(Flag.FastOrderState.CUSTOMER_PAYED);
                            orderStateTv.setText("确认发货");
                            handleOrderLayout.setVisibility(View.VISIBLE);
                            handleOrderBtn02.setText("确认发货");
                        }
                        break;
                        case 2: {//已发货,用户未确认收货
                            adapter.setState(Flag.FastOrderState.CUSTOMER_WAITING);
                            orderStateTv.setText("等待客户收货");
                        }
                        break;
                        case 3: {//交易完成 无法判断是否评价
                            adapter.setState(Flag.FastOrderState.BUSINESS_FINISHED);
                            orderStateTv.setText("交易已完成");
                        }
                        break;
                        case -1: {//订单取消
                            adapter.setState(Flag.FastOrderState.ORDER_CANCELED);
                            orderStateTv.setBackgroundColor(Color.LTGRAY);
                            orderStateTv.setText("订单已取消");
                        }
                        break;
                    }
                }
            }
            adapter.setNewData(detailBean.getGallery());
        } else {

        }
    }

    private String getInfoText(FastOrderDetailBean.AddressBean addressBean) {
        return addressBean.getRealname() + addressBean.getMobile() + "\n"
                + addressBean.getProvince() + addressBean.getArea() + addressBean.getCity()
                + addressBean.getTown() + addressBean.getAddress();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE})
    void startPickerFragment() {
        PhotoPickerFragment fragment = new PhotoPickerFragment();
        Bundle arguments = new Bundle();
        arguments.putInt(Global.Def.KEY_MAX, 1);
        fragment.setArguments(arguments);
        startForResult(fragment, RequestCode);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        FastOrderDetailPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == RequestCode) {
                List<Photo> photoList = data.getParcelableArrayList("photos");
                if (photoList != null && photoList.size() == 1) {
                    ImageView replyImg = (ImageView) adapter.getViewByPosition(selectPos, R.id.img_reply);
                    if (replyImg != null) {
                        String path = photoList.get(0).getFilePath();
                        Glide.with(_mActivity).load(path).into(replyImg);
                        replyImg.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
                        PictureHandler.upload(path, TAG + hashCode() + path);
                    }
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPicUploadResult(PicUploadResult result) {
        if (result.getSponsor().startsWith(TAG + hashCode())) {
            if (result.getValue() == Flag.Result.SUCCEED) {
                ImageView replyImg = (ImageView) adapter.getViewByPosition(selectPos, R.id.img_reply);
                if (replyImg != null) {
                    replyImg.clearColorFilter();
                }
                TextView addImgTv = (TextView) adapter.getViewByPosition(selectPos, R.id.tv_add_reply_img);
                if (addImgTv != null) {
                    addImgTv.setVisibility(View.GONE);
                }
                replyImgUrls.append(selectPos, result.getBean().getUrl());
            }
            selectPos = -1;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSetOrderResult(FastOrderSetResult event) {
        if (event.getValue() == Flag.Result.SUCCEED) {
            OrderHandler.requestFastOrderDetail(orderId);
        } else {
            Toast.makeText(_mActivity, "提交失败", Toast.LENGTH_SHORT).show();
        }
    }
}
